package reviewJDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-10-30
 * Time: 10:21
 */
public class MysqlSelect {
    public static void main(String[] args) throws SQLException {
        //1.找到数据库源
        DataSource dataSource =new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/milk?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("");
        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造sql语句
        String sql = "select * from student as s1,student as s2 ;";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4.执行sql
        //executeQuery返回的是一个数据集合---一张表
        ResultSet resultSet = statement.executeQuery();
        //5.遍历数据集合
        //遍历数据集合里的每一行
        while(resultSet.next()){
            //遍历每一行的每一列
            //根据列名 可读性更高
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int classId = resultSet.getInt("classId");
            //根据序号
//            int id = resultSet.getInt(1);
//            String name = resultSet.getString(2);
//            int classId = resultSet.getInt(3);
            System.out.println("id :"+id +" name:"+name +" classID:"+classId + "id :"+id +" name:"+name +" classID:"+classId );
        }
        //6.关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
